package ing.lightDogs.turetJson;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class AddTuret extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		try {
			Boolean confirmed = false;
			String address = req.getParameter("address");
			//TODO controllo sulle latitudini e longitudini
			Double latitude = Double.parseDouble(req.getParameter("latitude"));
			Double longitude = Double.parseDouble(req.getParameter("longitude"));
			String description = req.getParameter("description");
			String email = req.getParameter("email");
//			if (email==null) email="";
			Turet t = new Turet(address, description, latitude, longitude,confirmed,email);
			EntityManager em = EMFService.get().createEntityManager();
			// log.info("trying to insert in datastore");
			// TODO creare un classe Turet provvisorie da dover essere
			// confermate
			if (em.find(Turet.class, t.geohash) == null) {
				try {
					em.persist(t);
					resp.getWriter().println(
							t.toJson() + " inserted in the datastore");
				} finally {
					em.close();
				}
			} else {
				resp.getWriter().println(t.toJson() + " exists in datastore");
			}
		} 
		catch (NumberFormatException nfe) {
			resp.getWriter()
					.println(
							"latitude or longitude are not formatted as number "
									+ "please insert parameters in the form: "
									+ "http://localhost:8888/addturet?address=viapigna&latitude=123&longitude=3321");
		} 
		catch (NullPointerException npe) {
			resp.getWriter()
					.println(
							"address,latitude or longitude are null "
									+ "please insert parameters in the form: "
									+ "http://localhost:8888/addturet?address=viapigna&latitude=123&longitude=3321");
		}

	}

}
